package com.lagou.server;

import com.lagou.handler.UserServerHandler;
import com.lagou.request.JSONSerializer;
import com.lagou.request.RpcDecoder;
import com.lagou.request.RpcRequest;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;

public class ServerBootstrap {

//    public final static String zkAddr = "192.168.179.128:2181,192.168.179.128:2182,192.168.179.128:2183";
    public final static String zkAddr = "127.0.0.1:2181";
    public final static String baseNodeName = "/provider";
    public final static String nodeValue = "127.0.0.1:8990";
    public final static String ip = "127.0.0.1";
    public final static int port = 8990;


    public static void main(String[] args) throws InterruptedException {

        ZkClient zkClient = new ZkClient(zkAddr);
        System.out.println("会话被创建了..");
        //创建节点
        /* cereateParents : 是否要创建父节点，如果值为true,那么就会递归创建节点
         */
        if (!zkClient.exists(baseNodeName)) {
            zkClient.createPersistent(baseNodeName);
        }
        if (!zkClient.exists(baseNodeName + "/" +nodeValue)) {
            zkClient.createEphemeral(baseNodeName + "/" +nodeValue, nodeValue);
        }
        System.out.println("节点创建完成");

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        io.netty.bootstrap.ServerBootstrap serverBootstrap1 = new io.netty.bootstrap.ServerBootstrap();
        serverBootstrap1.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());

                    }
                });
        serverBootstrap1.bind(ip,port).sync();
    }

}
